<?php

class ConfigureController extends Controller
{
	protected $_navId = 'system';
	
	public function actionIndex()
	{
		$siteConfigForm = new SiteConfigForm();
		$siteConfig = SiteConfig::model()->find();
		if(!$siteConfig){
			$siteConfig = new SiteConfig();
		}
		
		$siteConfigForm->setValue($siteConfig);
		
		$postData = app()->request->getPost('SiteConfigForm', null);
		$info = null;
		if($postData){
			$siteConfigForm->attributes = $postData;
			if($siteConfigForm->email_type == SiteConfig::MAIL_SMTP){
				$siteConfigForm->setScenario('is_smtp');
			}				
			if($siteConfigForm->validate()){
				$changeToSmtp = false;
				if($siteConfigForm->email_type == SiteConfig::MAIL_SMTP){
					if($siteConfigForm->email_type != $siteConfig->email_type_value){
						$changeToSmtp = true;
					}
				}
				$siteConfig->attributes = $postData;
				if($siteConfig->save(false)){
					reLoadSiteConfig();
					$siteConfigForm->setValue($siteConfig);
					$info = 'Configuration Saved!';
					if($changeToSmtp){
						$user = app()->user->getData();
						app()->mail->sendConfirmation($user->id_user);
					}
					
					$siteConfig = SiteConfig::model()->find();
					if(!$siteConfig){
						$siteConfig = new SiteConfig();
					}
				}
			}
		}

		$this->render('index', array(
			'siteConfig' => $siteConfig,
			'siteConfigForm' => $siteConfigForm,
			'info' => $info,
		));
	}
	
	public function actionPurgeLogs()
	{
		if(app()->request->isAjaxRequest){
			$purgetime = app()->request->getPost('purgetime', null);
			if($purgetime){
				$now = time();
				switch($purgetime){
					case SiteConfig::PURGE_LOG_7DAY:
						$beforeTime = $now - (7 * 24 * 3600); break;
					case SiteConfig::PURGE_LOG_14DAY:
						$beforeTime = $now - (14 * 24 * 3600); break;
					case SiteConfig::PURGE_LOG_30DAY:
						$beforeTime = $now - (30 * 24 * 3600); break;
					case SiteConfig::PURGE_LOG_60DAY:
						$beforeTime = $now - (60 * 24 * 3600); break;
					default:
						$beforeTime = $now - (24 * 3600); break;
				}
				$loginLogsDeleted = LogLogin::model()->purge($beforeTime);
				$actionLogsDeleted = LogAction::model()->purge($beforeTime);
				
				$this->_returnAjax(array(
					'loginLogsDeleted' => $loginLogsDeleted,
					'actionLogsDeleted' => $actionLogsDeleted
				));
			}
		}
	}
	
	public function accessRules()
	{
		return array(
			array(
				'allow',
				'actions' => array('index', 'purgelogs'),
				'expression' => 'app()->user->isLogin() && app()->user->hasManageConfigPerm()',
				'redirect' => array('default/noaccess')
			),

			array(
				'deny',	//should be 'deny', 'allow' is used to give convenient to make test
				'users' => array('*'),
				'redirect' => array('user/login')
			)
		);
	}
}